import TauPage from '@/components/TauPage';
import TauActionPanel from '@/components/TauActionPanel';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Tab, Drawer } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { column } from './stores/definitions';
import { toJS } from 'mobx';
import ScDetailDrawer from '../../../../order/ScOrder/components/DetailDrawer';
import BusDetailDrawer from '../../../../order/BusOrder/components/DetailDrawer';
import CcDetailDrawer from '../../../../order/CcOrder/components/DetailDrawer';
import RsDetailDrawer from '../../../../order/RsOrder/components/DetailDrawer';
import DrawerFooter from '../../../../../components/DrawerFooter';

const tableId = uniqueId('tauTable-');

const tabItem = [
  { name: t`包车订单`, key: '1' },
  { name: t`专线订单`, key: '2' },
  { name: t`巴士订单`, key: '3' },
  { name: t`拼车订单`, key: '4' },
];

function Orders({ activity, onCancel, modal: orderMode }) {
  const { ordersStore: store } = useStore();
  const actRef = useRef();
  const [orderModal, setOrderModal] = useState([]);
  const [type, setType] = useState('');

  useEffect(() => {
    if (orderMode[1]?.startsWith?.('toClose')) handleCancel();
  }, [orderMode]);

  useEffect(() => {
    (async () => {
      await store.getBatches({ search: {} });
    })();
  }, []);
  // 获取列表数据
  const handleOnSearch = (params) => {
    const { upDate, getOnDate, ...searchArgs } = params.values;
    const [fromTime, toTime] = upDate || [];
    const [from, to] = getOnDate || [];
    store.search = {
      from,
      to,
      fromTime,
      toTime,
      activity: activity?.id,
      ...searchArgs,
    };
  };

  const orderColumn = {
    1: [
      { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
      {
        title: t`订单号`,
        width: 168,
        cell: (v, _, row) => {
          return (
            <Button key={row.id} type="primary" text onClick={() => handleTableAction(row, 'cc')}>
              {row.id}
            </Button>
          );
        },
      },
      column('ccOrder.orderType', { width: 58 }),
      column('ccOrder.routeText', { width: 78 }),
      column('ccOrder.subscribeName', { width: 58 }),
      column('company.name', { width: 78 }),
      column('price', { width: 78 }),
      column('ccOrder.orderStatus', { width: 58 }),
      column('partnerName', {
        width: 88,
        cell: (v, _, r) => {
          const { merchantName } = r;
          return <span>{t`${v} / ${merchantName}`}</span>;
        },
      }),
      column('source.targetType', { width: 68 }),
      column('crDate', { width: 124, sortable: true }),
      column('ccOrder.predictBeginDate', { width: 124, sortable: true }),
    ],
    2: [
      { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
      column('id', {
        width: 188,
        cell: (v, _, order) => {
          return (
            <Button text type="primary" onClick={() => handleTableAction(order, 'sc')}>
              {v}
            </Button>
          );
        },
      }),
      column('beginAreaName', {}),
      column('endAreaName', {}),
      column('companyName', { width: 128 }),
      column('scOrder.subscribeName', { width: 168 }),
      column('price', { width: 68 }),
      column('scOrder.orderStatus', { width: 88 }),
      column('scOrder.payTime', { width: 128 }),
      column('scOrder.shiftTime', { width: 168 }),
    ],
    3: [
      { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
      column('orderNumber', {
        width: 188,
        cell: (v, __, order) => {
          return <Button text type="primary" onClick={() => handleTableAction(order, 'bus')}>{v}</Button>;
        },
      }),
      column('busOrder.companyName', { width: 100 }),
      column('busOrder.type', { width: 58 }),
      column('busOrder.routeText', {}),
      column('busOrder.collectorName', { width: 88 }),
      column('price', { width: 118 }),
      column('busOrder.orderStatus', { width: 88 }),
      column('partnerName', { width: 88 }),
      column('crDate', { width: 124, sortable: true }),
      column('busOrder.shift.date', { width: 168, sortable: true }),
    ],
    4: [
      { title: t`编号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
      column('orderNumber', {
        width: 168,
        cell: (v, _, order) => {
          return <Button text type="primary" onClick={() => handleTableAction(order, 'rs')}>{v}</Button>;
        },
      }),
      column('rsOrder.startStationName', {
        width: 88,
        cell: (v, i, r) => {
          const { startMainAreaName, startMinorAreaName } = r;
          return <span>{t`${startMainAreaName}-${startMinorAreaName}`}</span>;
        },
      }),
      column('rsOrder.endStationName', {
        width: 88,
        cell: (v, i, r) => {
          const { endMainAreaName, endMinorAreaName } = r;
          return <span>{t`${endMainAreaName}-${endMinorAreaName}`}</span>;
        },
      }),
      column('rsOrder.subscribeName', { width: 58 }),
      column('companyName', { width: 58 }),
      column('price', { width: 118 }),
      column('rsOrder.orderStatus', { width: 58 }),
      column('partnerName', { width: 58 }),
      column('crDate', { width: 124, sortable: true }),
      column('rsOrder.predictBeginDate', { width: 124, sortable: true }),
    ],
  };

  const handleTableAction = (result, p) => {
    actRef.current = result;
    setType(p);
    setOrderModal(['view']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    onCancel?.();
  };

  // Modal窗口关闭回调
  const handleOrderCancel = () => {
    setOrderModal([]);
  };

  const orderViewDetail = {
    sc: <ScDetailDrawer
      modal={orderModal}
      handleCancel={handleOrderCancel}
      handleUpdate={() => { }}
      orderId={actRef?.current?.id}
      visible={!!orderModal[0]}
      onClose={() => {
        setOrderModal([]);
      }}
    />,
    bus: <BusDetailDrawer
      modal={orderModal}
      handleCancel={handleOrderCancel}
      handleUpdate={() => { }}
      orderId={actRef?.current?.id}
      visible={!!orderModal[0]}
      onClose={() => {
        setOrderModal([]);
      }}
    />,
    cc: <CcDetailDrawer
      modal={orderModal}
      handleCancel={handleOrderCancel}
      handleUpdate={() => { }}
      orderId={actRef?.current?.id}
      visible={!!orderModal[0]}
      onClose={() => {
        setOrderModal([]);
      }}
    />,
    rs: <RsDetailDrawer
      modal={orderModal}
      handleCancel={handleOrderCancel}
      handleUpdate={() => { }}
      orderId={actRef?.current?.id}
      visible={!!orderModal[0]}
      onClose={() => {
        setOrderModal([]);
      }}
    />,
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          {
            name: 'batchId',
            type: 'select',
            props: {
              dataSource: store.batches,
              placeholder: t`批次名称`,
              style: { width: 200 },
            },
          },
          {
            name: 'upDate',
            type: 'date-range',
            props: {
              placeholder: [t`开始上车时间`, t`结束上车时间`],
            },
          },
          {
            name: 'getOnDate',
            type: 'date-range',
            props: {
              placeholder: [t`开始下单时间`, t`结束下单时间`],
            },
          },
        ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <Tab
          activeKey={store.orderStatus}
          onChange={(v) => {
            store.data = [];
            store.orderStatus = v;
          }}
        >
          {tabItem?.map((item) => (
            <Tab.Item title={item?.name} key={item.key} />
          ))}
        </Tab>
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => {
            store.pg = pg;
          }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={orderColumn[store._orderStatus]}
        />
      </div>
      {orderViewDetail[type]}
      <DrawerFooter style={{ marginTop: 100 }}>
        <Button style={{ marginLeft: 8 }} onClick={() => handleCancel()}>{t`取消`}</Button>
      </DrawerFooter>
    </TauPage>
  );
}

export default observer(Orders);
